package com.miyake.dsp.otdr.ui;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JFrame;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JToggleButton;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import com.miyake.dsp.otdr.Fiber;
import com.miyake.dsp.otdr.FiberManager;
import com.miyake.dsp.otdr.FiberNode.NodeType;
import com.miyake.dsp.otdr.NodeProperties;
import com.miyake.dsp.otdr.OtdrSetting;
import com.miyake.dsp.ui.DspWidget;
import com.thoughtworks.xstream.XStream;

import javax.swing.ImageIcon;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;

public class OtdrSettingUI extends DspWidget {

	private static final long serialVersionUID = 1L;
	private JPanel jPanel = null;
	private MyPanel jPanel1 = null;

	private JButton selectedFiber;
	private FiberNodeUI root = null;  //  @jve:decl-index=0:
	private int marginX;
	private int marginY;
	private JToggleButton jToggleButton = null;
	private JToggleButton jToggleButton1 = null;
	private JToggleButton jToggleButton2 = null;
	private int grid = 8;
	private CursorMode cursorMode = CursorMode.Select;  //  @jve:decl-index=0:
	
	private int dragStartX;
	private int dragStartY;
	private int dragEndX;
	private int dragEndY;
	private Vector<JButton> selectedFibers;  //  @jve:decl-index=0:
	private JToggleButton jToggleButton3 = null;
	private JToggleButton jToggleButton4 = null;
	private JPopupMenu jPopupMenu = null;
	private JMenuItem jMenuItem5 = null;
	private JMenuItem jMenuItem6 = null;
	private JToggleButton jToggleButton5 = null;
	private JToggleButton jToggleButton6 = null;
	private JToggleButton jToggleButton7 = null;
	private JMenu jMenu3 = null;
	private JMenuItem jMenuItem9 = null;
	private JMenuItem jMenuItem10 = null;
	private JMenuItem jMenuItem11 = null;
	private JMenuItem jMenuItem12 = null;
	private JMenuItem jMenuItem16 = null;
	private JButton jButtonSave = null;
	private JPanel distanceRangePanel = null;
	
	private OtdrSetting setting;
	private FiberManager fiberManager;
	private final String fiberManagerXML = "FiberManager.xml";
	private FileSetup fileSetup;
	private JButton jButtonSaveAs;
	private JButton jButtonLoad;
	private JPanel jPanelToolBar;
	private JMenuItem jMenuItemRandom;
	
	private enum CursorMode {
		Select,
		Erase,
		Dragging,
		AddNone,
		AddFiber,
		AddCoupler,
		Add1x16Splliter,
		Add1x32Splliter,
		Add1x64Splliter,
		Cut,
	}
	
	private JPanel getDistanceRange() {
		if (distanceRangePanel == null) {
			distanceRangePanel = new JPanel();
			final JTextField text = new JTextField();
			text.setText(String.valueOf(setting.getDistanceRange()));
			distanceRangePanel.add(new JLabel("Distance Range"));
			distanceRangePanel.add(text);
			distanceRangePanel.setBounds(0, 0, 200, 40);
			text.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					setting.setDistanceRange(Double.valueOf(text.getText()));
					fireChange("");
				}
			});
		}
		return distanceRangePanel;
	}
	/**
	 * This method initializes jMenu3	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getJMenu3() {
		if (jMenu3 == null) {
			jMenu3 = new JMenu();
			jMenu3.setText("Change To");
			jMenu3.add(getJMenuItem12());
			jMenu3.add(getJMenuItem9());
			jMenu3.add(getJMenuItem10());
			jMenu3.add(getJMenuItem11());
			jMenu3.add(getJMenuItem16());
		}
		return jMenu3;
	}

	/**
	 * This method initializes jMenuItem9	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem9() {
		if (jMenuItem9 == null) {
			jMenuItem9 = new JMenuItem();
			jMenuItem9.setText("Connector");
			jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					changeToConnector();
				}
			});
		}
		return jMenuItem9;
	}

	/**
	 * This method initializes jMenuItem10	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem10() {
		if (jMenuItem10 == null) {
			jMenuItem10 = new JMenuItem();
			jMenuItem10.setText("ONU");
			jMenuItem10.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					changeToONU();
				}
			});
		}
		return jMenuItem10;
	}

	/**
	 * This method initializes jMenuItem11	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem11() {
		if (jMenuItem11 == null) {
			jMenuItem11 = new JMenuItem();
			jMenuItem11.setText("Terminated");
			jMenuItem11.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					changeToTerminated();
				}
			});
		}
		return jMenuItem11;
	}

	/**
	 * This method initializes jMenuItem12	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem12() {
		if (jMenuItem12 == null) {
			jMenuItem12 = new JMenuItem();
			jMenuItem12.setText("Open");
			jMenuItem12.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					changeToOpen();
				}
			});
		}
		return jMenuItem12;
	}

	/**
	 * This method initializes jMenuItem16	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem16() {
		if (jMenuItem16 == null) {
			jMenuItem16 = new JMenuItem();
			jMenuItem16.setText("Virtual Node");
			jMenuItem16.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					changeToVirtual();
				}
			});
		}
		return jMenuItem16;
	}

	public static void main(String arg[]) {
		OtdrSettingUI e = new OtdrSettingUI(new OtdrSetting(10e8, 1550, 10));
		//MainWindow e = new MainWindow();
		JFrame f = new JFrame();
		f.setVisible(true);
		f.setSize(600, 400);
		f.getContentPane().add(e);

	}
	
	/**
	 * This is the default constructor
	 */
	public OtdrSettingUI(OtdrSetting setting) {
		super();
		this.setting = setting;
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {	
		this.setSize(636, 474);
		this.setLayout(new BorderLayout());	
//		this.add(getDistanceRange(), BorderLayout.NORTH);
		this.add(getJPanelToolBar(), BorderLayout.NORTH);
		this.add(getJPanel(), BorderLayout.WEST);
		this.add(getJPanel1(), BorderLayout.CENTER);
		selectedFibers = new Vector<JButton>();
		fileSetup = new FileSetupXml();
		if (new File(fiberManagerXML).exists()) {
			this.readFiberManager();
		}
		else {
			fiberManager = new FiberManager();
		}
		
		if (new File("defaultFiber.xml").exists()) {
			this.readSetups("defaultFiber.xml");
		}
		else {
			this.addOTDR(20, 100);
		}
		
		root.getFiberNode().setWavelength(setting.getWavelength());
	}


	private Component getJPanelToolBar() {
		if (jPanelToolBar == null) {
			jPanelToolBar = new JPanel();
			jPanelToolBar.setLayout(new FlowLayout());
//			jPanelToolBar.setPreferredSize(new Dimension(122, 400));
			jPanelToolBar.add(getJButtonSaveAs());
			jPanelToolBar.add(getJButtonLoad());			
			jPanelToolBar.add(getJToggleButtonSave());
		}
		return jPanelToolBar;
	}
	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			//jPanel.setLayout(null);
			jPanel.setLayout(new FlowLayout());
			jPanel.setPreferredSize(new Dimension(122, 400));
			jPanel.add(getJToggleButton(), null);
			jPanel.add(getJToggleButton5(), null);
			jPanel.add(getJToggleButton6(), null);
			jPanel.add(getJToggleButton1(), null);
			jPanel.add(getJToggleButton2(), null);
			jPanel.add(getJToggleButton3(), null);
			jPanel.add(getJToggleButton4(), null);
			jPanel.add(getJToggleButton7(), null);
			

//			jPanel.add(getJCheckButtonPulse(), null);
		}
		return jPanel;
	}



	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private MyPanel getJPanel1() {
		if (jPanel1 == null) {
			jPanel1 = new MyPanel();
			jPanel1.setBackground(Color.white);
			jPanel1.setLayout(null);
			jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {   
				public void mouseReleased(java.awt.event.MouseEvent e) {    
					if (cursorMode == CursorMode.AddFiber) {
						addNode(e.getX(), e.getY(), NodeType.Open);
					}
					else if (cursorMode == CursorMode.AddNone) {
						addNode(e.getX(), e.getY(), NodeType.None);
					}					
					else if (cursorMode == CursorMode.AddCoupler) {
						addSplitter(e.getX(), e.getY(),2);
					}
					else if (cursorMode == CursorMode.Add1x16Splliter) {
						addSplitter(e.getX(), e.getY(), 16);
					}
					else if (cursorMode == CursorMode.Add1x32Splliter) {
						addSplitter(e.getX(), e.getY(), 32);
					}
					else if (cursorMode == CursorMode.Add1x64Splliter) {
						addSplitter(e.getX(), e.getY(), 64);
					}
					else if (cursorMode == CursorMode.Dragging) {
						cursorMode = CursorMode.Select;
						repaint();
					}

				}
				public void mousePressed(java.awt.event.MouseEvent e) {
					if (cursorMode == CursorMode.Select) {
						dragStartX = e.getX();
						dragStartY = e.getY();
						dragEndX = dragStartX;
						dragEndY = dragStartY;
						
						cursorMode = CursorMode.Dragging;
						selectedFibers.removeAllElements();
						selectedFiber = null;
						root.cancelSelection();
						repaint();
					}
					else if (cursorMode == CursorMode.Dragging) {

					}
				}
			});
			jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
				public void mouseDragged(java.awt.event.MouseEvent e) {
					dragEndX = e.getX();
					dragEndY = e.getY();

					if (cursorMode == CursorMode.Dragging) {
						selectedFibers.removeAllElements();
						root.select(dragStartX, dragStartY, 
								dragEndX, dragEndY, selectedFibers);
					}
					repaint();
				}
				
			});
			jPanel1.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyReleased(java.awt.event.KeyEvent e) {
					System.out.println("keyReleased()"); // TODO Auto-generated Event stub keyReleased()
				}
			});
		}
		return jPanel1;
	}

	class MyPanel extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 6092970528284255284L;

		/* (non-Javadoc)
		 * @see javax.swing.JComponent#paint(java.awt.Graphics)
		 */
		@Override
		public void paint(Graphics arg0) {
			// TODO Auto-generated method stub
			super.paint(arg0);
			
			drawGrid(arg0);
			if (root != null) {
				root.drawLine(arg0);
			}
			
			if (cursorMode == CursorMode.Dragging) {
				arg0.drawRect(dragStartX, dragStartY, 
						dragEndX - dragStartX, dragEndY - dragStartY);
			}
		}

		private void drawGrid(Graphics g) {
			// TODO Auto-generated method stub
			g.setColor(Color.GRAY);
			for (int x = 0; x < this.getWidth(); x += grid) {
				for (int y = 0; y < this.getHeight(); y += grid) {
					g.drawLine(x, y, x, y);
				}
			}
			g.setColor(Color.BLACK);
		}
		
		public void clear() {
			this.removeAll();
		}
	}
	
	private int roundPosition(int x) {
		return x / grid * grid;
	}
	
	private void fiberMoved(int x, int y, JButton object) {
		int xx = selectedFiber.getX()+x - marginX;
		int yy = selectedFiber.getY()+y - marginY;
		xx = roundPosition(xx);
		yy = roundPosition(yy);
		selectedFiber.setLocation(xx, yy);		
		
		for (int i = 0; i < selectedFibers.size(); i++) {
			JButton button = (JButton)selectedFibers.elementAt(i);
			if (object != button) {
				xx = button.getX()+x - marginX;
				yy = button.getY()+y - marginY;
				xx = xx / grid * grid;
				yy = yy / grid * grid;	
				button.setLocation(xx, yy);
			}
		}
		
		this.getJPanel1().repaint();
	}
	
	private void addSplitter(int x, int y, int count) {
		
		addNode(x, y, NodeType.Splitter);
		FiberNodeUI active = root.findFiber(selectedFiber);
//		active.setType(NodeType.Splitter);
		active.getProperties().setLoss(0.5);
		for (int i = 0; i < count; i++) {
			selectedFiber = active.getReference();
			root.setSelected(active.getReference());
			addNode(x + 16, y - (i-count/2) * 16, NodeType.None);
		}
		fireChange("");
	}
	
	private void addOTDR(int x, int y) {
		JButton fiber = new JButton();
		fiber.setBounds(new Rectangle(roundPosition(x - 8), roundPosition(y - 8), 16, 16));
		fiber.setBackground(Color.white);
		this.setButtonListeners(fiber);
		this.getJPanel1().repaint();
		root  = new FiberNodeUI(NodeType.OTDR, new NodeProperties(fiberManager.getFiber("Default")), fiber);	
		root.setRoot(true);
		setting.setEntryPoint(root.getFiberNode());
		selectedFiber = fiber;		
	}
	
	private FiberNodeUI addNode(int x, int y, NodeType type) {
		if (selectedFiber == null && root != null)
			return null;
		
		JButton fiber = new JButton();
		fiber.setBounds(new Rectangle(roundPosition(x - 8), roundPosition(y - 8), 16, 16));
		fiber.setBackground(Color.white);
		this.setButtonListeners(fiber);
		this.getJPanel1().repaint();

		FiberNodeUI newFiber = null;
		if (root == null) {
			root  = new FiberNodeUI(NodeType.OTDR, new NodeProperties(fiberManager.getFiber("Default")), fiber);	
			root.setRoot(true);
			selectedFiber = fiber;
		}
		else {
			newFiber = new FiberNodeUI(NodeType.Connector, new NodeProperties(fiberManager.getFiber("Default")), fiber);
			newFiber.setType(type);
			newFiber.getFiberNode().setWavelength(setting.getWavelength());
			if (root.findFiber(selectedFiber).addNode(newFiber)) {
				selectedFiber = fiber;
			}
		}
		root.setSelected(fiber);
		
		this.getJPanel1().repaint();
		
		fireChange("");
		
		return newFiber;
		
	}


	/**
	 * This method initializes jToggleButton	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton() {
		if (jToggleButton == null) {
			jToggleButton = new JToggleButton();
			jToggleButton.setText("Selection");
			jToggleButton.setIcon(new ImageIcon("select.PNG"));
			jToggleButton.setBounds(new Rectangle(0, 0, 121, 31));
			jToggleButton.setMnemonic(KeyEvent.VK_UNDEFINED);
			jToggleButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton);
					cursorMode = CursorMode.Select;
				}
			});
		}
		return jToggleButton;
	}

	/**
	 * This method initializes jToggleButton1	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton1() {
		if (jToggleButton1 == null) {
			jToggleButton1 = new JToggleButton();
			jToggleButton1.setText("Connector");
			jToggleButton1.setPreferredSize(new Dimension(100, 26));
			jToggleButton1.setBounds(new Rectangle(0, 105, 121, 31));
			jToggleButton1.setHorizontalTextPosition(SwingConstants.TRAILING);
			jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton1);
					cursorMode = CursorMode.AddFiber;
				}
			});
		}
		return jToggleButton1;
	}

	/**
	 * This method initializes jToggleButton2	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton2() {
		if (jToggleButton2 == null) {
			jToggleButton2 = new JToggleButton();
			jToggleButton2.setText("1x2 Coupler");
			jToggleButton2.setBounds(new Rectangle(0, 135, 121, 31));
			jToggleButton2.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton2);
					cursorMode = CursorMode.AddCoupler;
				}
			});
		}
		return jToggleButton2;
	}

	private void deleteComponent() {
		if (selectedFiber != null && root.findFiber(selectedFiber).getNodeType() != NodeType.OTDR) {
			this.getJPanel1().remove(selectedFiber);
			root.remove(selectedFiber);
		}
		
		for (int i = 0; i < selectedFibers.size(); i++) {
			JButton button = (JButton)selectedFibers.elementAt(i);
			if (button != selectedFiber && root.findFiber(button).getNodeType() != NodeType.OTDR) {
				this.getJPanel1().remove(button);
				root.remove(button);
			}
		}
		this.getJPanel1().repaint();
		
		fireChange("");
	}
	private void showPropertiesDlg() {
		if (selectedFiber == null) {
			return;
		}
		
		NodeType type  = root.findFiber(selectedFiber).getNodeType();
		if (type == NodeType.Connector || type == NodeType.APC || 
				type == NodeType.ONU || type == NodeType.Open) {
			
			FiberPropertiesPanel panel = new FiberPropertiesPanel(root.getSelectedProperties(), fiberManager);
			OtdrSettingFrame dlg = new OtdrSettingFrame(panel);
			dlg.setVisible(true);
			panel.addHandler(new DspWidgetHandler() {
				@Override
				public void onChange(String value) {
					jPanel1.repaint();
					fireChange("");
				}	
			});

		}
		else if (type == NodeType.Splitter) {
			FiberPropertiesPanel panel = new FiberPropertiesPanel(root.getSelectedProperties(), fiberManager);
			OtdrSettingFrame dlg = new OtdrSettingFrame(panel);
			dlg.setVisible(true);
			panel.addHandler(new DspWidgetHandler() {
				@Override
				public void onChange(String value) {
					jPanel1.repaint();
					fireChange("");
				}	
			});
		
		}
		else if (type == NodeType.OTDR) {
			OtdrPropertyPanel panel = new OtdrPropertyPanel(setting);
			OtdrSettingFrame dlg = new OtdrSettingFrame(panel);
			dlg.setVisible(true);
			root.updateFiber(fiberManager);
			panel.addHandler(new DspWidgetHandler() {
				@Override
				public void onChange(String value) {
					root.getFiberNode().setWavelength(setting.getWavelength());
					repaint();
					fireChange(value);
				}
			});
			dlg.pack();
		}
	}
	
	/**
	 * This method initializes jToggleButton3	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton3() {
		if (jToggleButton3 == null) {
			jToggleButton3 = new JToggleButton();
			jToggleButton3.setText("1x16 Splitter");
			jToggleButton3.setBounds(new Rectangle(0, 165, 121, 31));
			jToggleButton3.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton3);
					cursorMode = CursorMode.Add1x16Splliter;
				}
			});
		}
		return jToggleButton3;
	}

	private void releaseButtons(JToggleButton me) {
		for (int i = 0; i < this.getJPanel().getComponentCount(); i++) {
			if (this.getJPanel().getComponent(i) instanceof JToggleButton) {
				((JToggleButton)this.getJPanel().getComponent(i)).setSelected(false);
			}
		}
		
		me.setSelected(true);
	}
	
	private void saveFiberManager() {
		XStream xstream = new XStream();
    	String xml = xstream.toXML(fiberManager);
    	try {
			BufferedWriter writeFile = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(fiberManagerXML)));	
			writeFile.write(xml);
			writeFile.close();	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
	    }
	}
	
	private void readFiberManager() {
		XStream xstream = new XStream();
    	
		BufferedReader reader = null;
		String tmp = "";
		String xml2 = "";

		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(fiberManagerXML)));
			while((tmp = reader.readLine()) != null) {
				xml2 += tmp;
			}
			fiberManager = (FiberManager)xstream.fromXML(xml2);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();		
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	private void saveSetups(String filename) {
		root.update();
		fileSetup.save(filename, root);
	}

	private void readSetups(String filename) {	
		root = fileSetup.load(filename);
		setting.setEntryPoint(root.getFiberNode());
		root.createButton();
		
		Vector<JButton> v = new Vector<JButton>();
		root.getButtons(v);
		for (int i = 0; i < v.size(); i++) {
			this.setButtonListeners(v.elementAt(i));
		}
		repaint();
	}
	
	private void setButtonListeners(JButton fiber) {
		fiber.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
			public void mouseDragged(java.awt.event.MouseEvent e) {
				fiberMoved(e.getX(), e.getY(), (JButton)e.getSource());
			}
		});
		fiber.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mousePressed(java.awt.event.MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e)) {

				}
				else if (SwingUtilities.isRightMouseButton(e)) {
					getJPopupMenu().show(e.getComponent(), e.getX(), e.getY());
					
					if (selectedFibers.size() > 1) {
						return;
					}
				}
				
				selectedFiber = (JButton)e.getSource();
				marginX = e.getX();
				marginY = e.getY();
				root.setSelected(selectedFiber);

			}
			public void mouseReleased(java.awt.event.MouseEvent e) {
				if (SwingUtilities.isRightMouseButton(e)) {
					if (selectedFibers.size() > 1) {
						return;
					}
				}
				
				if (cursorMode == CursorMode.Erase) {
					deleteComponent();
				}
				selectedFibers.removeAllElements();
			}
		});
		fiber.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyReleased(java.awt.event.KeyEvent e) {
				if (e.getKeyCode() == 127) {
					deleteComponent();
				}
			}
		});		
		
		this.getJPanel1().add(fiber);
	}
	/**
	 * This method initializes jToggleButton4	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton4() {
		if (jToggleButton4 == null) {
			jToggleButton4 = new JToggleButton();
			jToggleButton4.setText("1x32 Splitter");
			jToggleButton4.setBounds(new Rectangle(0, 195, 121, 31));
			jToggleButton4.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton4);
					cursorMode = CursorMode.Add1x32Splliter;
				}
			});
		}
		return jToggleButton4;
	}
	
	/**
	 * This method initializes jPopupMenu	
	 * 	
	 * @return javax.swing.JPopupMenu	
	 */
	private JPopupMenu getJPopupMenu() {
		if (jPopupMenu == null) {
			jPopupMenu = new JPopupMenu();
			jPopupMenu.add(getJMenuItem5());
			jPopupMenu.add(getJMenuItem6());
			jPopupMenu.add(getJMenu3());
			jPopupMenu.add(getJMenuAddRandom());
		}
		return jPopupMenu;
	}

	private JMenuItem getJMenuAddRandom() {
		if (jMenuItemRandom == null) {
			jMenuItemRandom = new JMenuItem();
			jMenuItemRandom.setText("Add wild fiber");
			jMenuItemRandom.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					addRandomFiber();
				}
			});
		}
		return jMenuItemRandom;
	}
	protected void addRandomFiber() {
		
		for (JButton button : this.selectedFibers) {
			this.selectedFiber = button;
			FiberNodeUI node = addNode(button.getX()+50, button.getY()+8, NodeType.Connector);
			double length = Math.abs(Math.random());
			length = ((int)(length*100))/100.0;
			node.getFiberNode().getProperties().setLength(length);
		}
	}
	/**
	 * This method initializes jMenuItem5	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem5() {
		if (jMenuItem5 == null) {
			jMenuItem5 = new JMenuItem();
			jMenuItem5.setText("Properties");
			jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					showPropertiesDlg();
				}
			});
		}
		return jMenuItem5;
	}

	/**
	 * This method initializes jMenuItem6	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItem6() {
		if (jMenuItem6 == null) {
			jMenuItem6 = new JMenuItem();
			jMenuItem6.setText("Delete");
			jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					deleteComponent();
				}
			});
		}
		return jMenuItem6;
	}

	/**
	 * This method initializes jToggleButton5	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton5() {
		if (jToggleButton5 == null) {
			jToggleButton5 = new JToggleButton();
			jToggleButton5.setText("Eraser");
			jToggleButton5.setBounds(new Rectangle(0, 30, 121, 31));
			jToggleButton5.setIcon(new ImageIcon("eraser2.PNG"));
			jToggleButton5.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton5);
					cursorMode = CursorMode.Erase;
				}
			});
		}
		return jToggleButton5;
	}

	/**
	 * This method initializes jToggleButton6	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton6() {
		if (jToggleButton6 == null) {
			jToggleButton6 = new JToggleButton();
			jToggleButton6.setText("Virtual Node");
			jToggleButton6.setBounds(new Rectangle(0, 75, 121, 31));
			jToggleButton6.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton6);
					cursorMode = CursorMode.AddNone;
				}
			});
		}
		return jToggleButton6;
	}

	/**
	 * This method initializes jToggleButton7	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton7() {
		if (jToggleButton7 == null) {
			jToggleButton7 = new JToggleButton();
			jToggleButton7.setText("OTDR");
			jToggleButton7.setBounds(new Rectangle(0, 240, 121, 31));
			jToggleButton7.setIcon(new ImageIcon("otdr.PNG"));
			jToggleButton7.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					releaseButtons(jToggleButton7);
				}
			});
			
		}
		return jToggleButton7;
	}

	private JButton getJToggleButtonSave() {
		if (jButtonSave  == null) {
			jButtonSave = new JButton();
			jButtonSave.setText("Save as default");
			jButtonSave.setBounds(new Rectangle(0, 240+30, 121, 31));
			//jToggleButtonSave.setIcon(new ImageIcon("otdr.PNG"));
			jButtonSave.addActionListener(new java.awt.event.ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					saveSetups("defaultFiber.xml");
					saveFiberManager();
				}
			});
			
		}
		return jButtonSave;
	}
	
	private JButton getJButtonSaveAs() {
		if (jButtonSaveAs == null) {
			jButtonSaveAs = new JButton();
			jButtonSaveAs.setText("Save");
			jButtonSaveAs.setBounds(new Rectangle(0, 240+60, 121, 31));
			jButtonSaveAs.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					saveSetupAs();
				}
			
			});
		}
		return jButtonSaveAs;
	}
	
	private JButton getJButtonLoad() {
		if (jButtonLoad == null) {
			jButtonLoad = new JButton();
			jButtonLoad.setText("Load");
			jButtonLoad.setBounds(new Rectangle(0, 240+90, 121, 31));
			jButtonLoad.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					readSetupAs();
				}			
			});
		}
		return jButtonLoad;
	}
	
	protected void saveSetupAs() {
	    JFileChooser chooser = new JFileChooser();
	    FileNameExtensionFilter filter = new FileNameExtensionFilter(
	        "Fiber Setup", "fsp");
	    chooser.setFileFilter(filter);
	    int returnVal = chooser.showSaveDialog(this);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	String filename = chooser.getSelectedFile().getAbsolutePath();
	    	if (!filename.substring(filename.length() - 4, filename.length()).equalsIgnoreCase(".fsp")) {
	    		filename += ".fsp";
	    	}
	    	saveSetups(filename);
	    }
	}
	
	protected void readSetupAs() {
		this.getJPanel1().clear();
	    JFileChooser chooser = new JFileChooser();
	    FileNameExtensionFilter filter = new FileNameExtensionFilter(
	        "Fiber Setup", "fsp");
	    chooser.setFileFilter(filter);
	    int returnVal = chooser.showOpenDialog(this);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	String filename = chooser.getSelectedFile().getAbsolutePath();
	    	readSetups(filename);
	    }		
	    setting.setEntryPoint(root.getFiberNode());
	    fireChange("");
	}
	
	private void changeToVirtual() {
		if (this.selectedFiber != null) {
			root.findFiber(selectedFiber).setType(NodeType.None);
		}		
		Iterator<JButton> it = selectedFibers.iterator();
		while(it.hasNext()) {
			FiberNodeUI node = root.findFiber(it.next());
			if (node.getNodeType() != NodeType.OTDR) {
				node.setType(NodeType.None);
			}
		}
		fireChange("");
	}
	
	private void changeToTerminated() {
		if (this.selectedFiber != null) {
			root.findFiber(selectedFiber).setType(NodeType.APC);
		}		
		Iterator<JButton> it = selectedFibers.iterator();
		while(it.hasNext()) {
			FiberNodeUI node = root.findFiber(it.next());
			if (node.getNodeType() != NodeType.OTDR) {
				node.setType(NodeType.APC);
			}
		}
		fireChange("");
	}

	private void changeToOpen() {
		if (this.selectedFiber != null) {
			root.findFiber(selectedFiber).setType(NodeType.Open);
		}	
		Iterator<JButton> it = selectedFibers.iterator();
		while(it.hasNext()) {
			FiberNodeUI node = root.findFiber(it.next());
			if (node.getNodeType() != NodeType.OTDR) {
				node.setType(NodeType.Open);
			}
		}
		fireChange("");
	}
	
	private void changeToConnector() {
		if (this.selectedFiber != null) {
			root.findFiber(selectedFiber).setType(NodeType.Connector);
		}
		Iterator<JButton> it = selectedFibers.iterator();
		while(it.hasNext()) {
			FiberNodeUI node = root.findFiber(it.next());
			if (node.getNodeType() != NodeType.OTDR) {
				node.setType(NodeType.Connector);
			}
		}
		fireChange("");
	}
	
	private void changeToONU() {
		if (this.selectedFiber != null) {
			root.findFiber(selectedFiber).setType(NodeType.ONU);
		}		
		Iterator<JButton> it = selectedFibers.iterator();
		while(it.hasNext()) {
			FiberNodeUI node = root.findFiber(it.next());
			if (node.getNodeType() != NodeType.OTDR) {
				node.setType(NodeType.ONU);
			}
		}
		fireChange("");
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
